import 'dart:async';

import 'package:flutter/material.dart';

import 'index.dart';

typedef InputChange = Widget Function(BuildContext context, double inputHeight, bool inputClose);

/// @Author 杨璐铭
/// @Date 2023/6/23 4:37 PM
/// @describe 键盘监听
class CommonInputListener extends StatefulWidget {
  const CommonInputListener({
    required this.inputChange,
    this.delayCheckMilliseconds = 36,
    Key? key,
  }) : super(key: key);

  final InputChange inputChange;
  final int delayCheckMilliseconds;

  @override
  State<CommonInputListener> createState() => _CommonInputListenerState();
}

class _CommonInputListenerState extends State<CommonInputListener> with WidgetsBindingObserver {
  Timer? checkoutInputHeight;
  double inputHeight = 0;

  double get insertBottom => MediaQueryData.fromWindow(WidgetsBinding.instance.window).viewInsets.bottom;

  void check() {
    checkoutInputHeight = Timer.periodic(Duration(milliseconds: widget.delayCheckMilliseconds), (_) {
      setState(() {
        checkoutInputHeight?.cancel();
        checkoutInputHeight = null;
        if (inputHeight == 0 && insertBottom > 0) {
          Log.log('-----记录输入法高度 : $insertBottom');
          inputHeight = insertBottom;
        }
      });
    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    if (inputHeight == 0 && 0 == insertBottom) return;
    setState(() {
      if (checkoutInputHeight == null) {
        check();
      } else {
        if (checkoutInputHeight!.isActive) {
          checkoutInputHeight!.cancel();
          check();
        }
      }
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    checkoutInputHeight?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return widget.inputChange(context, inputHeight, 0 == insertBottom);
  }
}
